import React, { Component } from 'react'
import { Layout, Modal, Input, Radio, Button } from 'antd';
import style from './UserCenter.module.less'
import { FormOutlined } from '@ant-design/icons';
// import th from '@assets/image/th.jpg'
import {UserCenterRequest, UserImgRequest, UserModifRequest} from "@requests/auth";
import {toast} from "react-toastify";
import {withRouter} from "react-router-dom";
import {connect} from "react-redux";
import logon from "@pages/Login/components/logon";
import {ModifyUser} from "@creators/userCreator";

 class UserCenter extends Component {
    state = {
        //请求用户基本数据状态
        userCenterState:'idle',
        // 请求用户基本状态的错误异常
        userCenterError:null,
        user:this.props.user,
        // 获取用户基本数据
        userInfo : {},
        // 上传图片
        user_img:null,
        // 修改用户基本数据
        userCenter:{
            id:'',
            gender:'0',
            signature:'',
            userImg:'',
        }
    }
    componentDidMount() {
        let user = JSON.parse(sessionStorage.getItem("user"))
        console.log(user)
        // console.log(this.state)

        console.log(this.state.user.id)
        //页面初始化请求用户数据
        this.userCenterRequest(this.state.user.id)
    }

    userCenterRequest = async(username) => {
        if(this.state.userCenterState === 'loading') return
        this.setState({
            userCenterState:'loading',
            userCenterError:null
        })
        try {
            let response = await UserCenterRequest(username)

            this.setState({
                userCenterState:'success',
                userCenterError:null
            })
            // console.log(response)
            this.setState({
                userInfo:{
                    ...response.userInfo
                },
            })
        } catch (error){
            this.setState({
                userCenterState:'Error',
                userCenterError : error.message
            })
            return toast('获取用户信息失败',{autoClose:1000})
        }

    }
    onChange = (event) => {
        this.setState({
            userCenter : {
                ...this.state.userCenter,
                [event.target.name] : event.target.value
            }
        })
    };
    handleFileChange = (event) => {
        const maxFileSize = 3 * 1024 * 1024
        const file = event.target.files[0]
        if(file > maxFileSize){
            return   toast.warn('图片上传大小超过限制！', {
                autoClose: 1000,
            });
        }
         this.setState({
             user_img: file
         });
     };
    onSubmit =async () => {
        const formdata = new FormData()
        let response1 = {}
        if (this.state.user_img !== null){
            formdata.append("user_img",this.state.user_img)
            response1 = await UserImgRequest(formdata)
            if(response1.code === 400){
                return console.log(response1.errmsg)
            }
            console.log(response1)
            this.setState({
                userCenter:{
                    ...this.state.userCenter,
                    userImg:response1.userImg
                }
            })
        }

    }
    handleUpload = () => {
        this.onSubmit()
        this.setState({
            userCenter:{
                ...this.state.userCenter,
                id:this.state.userInfo.id
            }
        })
        setTimeout(async () => {
            const response = await UserModifRequest(this.state.userCenter)
            if(response.code === 200){
                toast.success("修改成功", {
                    // 自定关闭事件
                    autoClose: 1000
                });
                return
            }
            console.log(this.state.userCenter)
            this.props.dispatch(ModifyUser(this.state.userCenter))
            toast.success("修改成功", {
                // 自定关闭事件
                autoClose: 1000
            });
            this.props.history.replace('/')
        },100)

         // 发送图片到后端
         // 使用fetch、axios或其他HTTP库发送formData到后端API
     };
    render() {
        const { Content } = Layout;
        const { TextArea } = Input;
        return (
            <Layout
                style={{
                    padding: '0 24px 24px',
                }}
            >

                <p style={{
                    margin: '16px 0',
                }}>编辑资料</p>
                <Content
                    style={{
                        padding: 24,
                        margin: 0,
                        minHeight: 280,
                        background: 'white',
                    }}
                >
                    <div className={style.User_box}>
                        <div className={style.User_top}>
                            <div className={style.User_photo}>
                                    <div ><img src={`${process.env.REACT_APP_BASE_URL}${this.state.userInfo.userImg}`} style={{objectFit:"cover"}} alt=""  />
                                    <p ><input  type="file" name='file' accept="image/jpeg,image/jpg,image/png" onChange={this.handleFileChange}  style = {{width : "50%",border:0}}/><FormOutlined /></p></div>
                            </div>
                        </div>
                        <div className={style.User_bottom}>
                            <div className={style.center}>
                                {/*<div>*/}
                                {/*    昵称：<Input style={{ width: '60%' }} showCount maxLength={10} name='username' onChange={this.onChange} placeholder={this.state.userInfo.username}  value={this.state.userCenter.username}/>*/}
                                {/*</div>*/}
                                <div>
                                    性别：
                                    <input type="radio" name="gender" value='0' checked={this.state.userCenter.gender === '0'} onChange={this.onChange}
                                           id="radio1"/>
                                    <label htmlFor="radio1">男</label>
                                    <input type="radio" style={{marginLeft:'5%'}} name="gender" value='1' checked={this.state.userCenter.gender === '1'} onChange={this.onChange} id="radio2"/>
                                    <label htmlFor="radio2">女</label>
                                </div>
                                <div>
                                    个性签名：<TextArea
                                        showCount
                                        name='signature'
                                        maxLength={50}
                                        style={{
                                            height: 80,
                                            marginBottom: 24,
                                            width: 310
                                        }}
                                        onChange={this.onChange}
                                        value = {this.state.userCenter.signature}
                                        placeholder="个性的人，个性的名"
                                    />

                                </div>
                                <button className={style.buttons} type="button"  onClick={this.handleUpload}>
                                    保存修改
                                </button>
                            </div>
                        </div>
                    </div>
                </Content>
            </Layout>
        )
    }
}


const mapStateToProps = (state) => ({
    user : state.userReducer.user
})
export default connect(mapStateToProps,undefined)(withRouter(UserCenter))
